<template>
  <n-card :bordered="false" class="proCard">
    <!--表单部分,可以动态创建表单-->
    <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
      <template #statusSlot="{ model, field }">
        <n-input v-model:value="model[field]" />
      </template>
    </BasicForm>

    <!--展示信息部分-->
    <BasicTable
      :columns="columns"
      :request="loadDataTable"
      :row-key="(row:ListData) => row.id"
      ref="actionRef"
      :actionColumn="actionColumn"
      @update:checked-row-keys="onCheckedRow"
      :scroll-x="1090"
    >
      <template #tableTitle>
        <n-button type="primary" @click="exportGroup" style="margin-right: 10px;">导出数据</n-button>
        <n-upload ref="uploadComponent" action="#" :custom-request="customRequest"  accept=".xlsx" :show-file-list="false">
          <n-button type="primary" @click="reloadTable" >导入数据</n-button>
        </n-upload>

      </template>
      <template #deletedata>

      </template>
      <template #toolbar>
        <n-button type="primary" @click="showUserdrawer" style="margin-right: 10px;">
          新建
        </n-button>
        <n-button type="primary" :disabled="isRowKeysEmpty" @click="batchDelete" style="margin-right: 10px;"> 删除 </n-button>
        
        <n-button type="primary" @click="reloadTable" >刷新数据</n-button>
      </template>
    </BasicTable>

    <n-drawer v-model:show="showdrawer" :width="600">
      <n-drawer-content :title="titledrawer" closable>
        <n-form
          :model="formParams"
          :rules="rules"
          ref="formRef"
          label-placement="left"
          :label-width="100"
          class="py-4"
        >
          <n-grid :cols="24" :x-gap="24">
            <n-form-item-gi :span="12" label="项目名称" path="project">
              <n-select
                v-model:value="formParams.project"
                placeholder="请选择项目"
                :options="selectProjectOptions"
                :clearable="true"
                :disabled="projectReadOnly"
              />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="班组名称" path="group">
              <n-select
                v-model:value="formParams.group"
                placeholder="请选择班组"
                :options="selectGroupOptions"
                :clearable="true"
                :disabled="groupReadOnly"
              />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="班组长" path="groupleader">
              <n-input placeholder="请输入姓名" v-model:value="formParams.groupleader" :clearable="true" />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="班组人数" path="groupstaffsize">
              <n-input type="number" placeholder="请输入班组人数" v-model:value="formParams.groupstaffsize" :clearable="true"/>
            </n-form-item-gi>
          </n-grid>

        </n-form>
        <template #footer>
          <n-button type="primary" @click="saveuserinfo"> 提交 </n-button>
        </template>
      </n-drawer-content>
    </n-drawer>
  </n-card>
</template>

<script lang="ts" setup>
  import { h, onMounted, reactive, ref, computed } from 'vue';
  import { BasicTable, TableAction } from '@/components/Table';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import {
    getTableList,
    getProjcetOptions,
    getGroupOptions,
    batchDelGroup,
    createGroup,
    updateGroup,
    uploadGroupExcel,
    getGroupExcel,
  } from '@/api/project/group';
  import { columns, ListData } from './group_columns';
  import { type FormRules } from 'naive-ui';


  const selectProjectOptions = ref([]);
  const selectGroupOptions = ref([]);
  // 获取第一个下拉框的选项数据
  onMounted(async () => {
    try {
      const projectoptions = await getProjcetOptions({});
      selectProjectOptions.value = projectoptions;
      const groupoptions = await getGroupOptions({});
      selectGroupOptions.value = groupoptions;
    } catch (error) {
      console.error('Failed to fetch project options:', error);
    }
  });

  const projectReadOnly = ref(false);
  const groupReadOnly = ref(false);

  const schemas: FormSchema[] = [
    {
      field: 'selectProject',
      component: 'NSelect',
      label: '选择项目',
      componentProps: {
        clearable: false,
        placeholder: '请选择项目',
        options: selectProjectOptions,
        onUpdateValue: (e: any) => {
          console.log('selectProjectOptions', e);
        },
      },
    },
  ];
  const [register, { getFieldsValue }] = useForm({
    gridProps: { cols: '3 s:3 m:4 l:5 xl:6 2xl:7' },
    labelWidth: 90,
    schemas,
    showAdvancedButton: false,
  });

  const formRef: any = ref(null);
  const actionRef = ref();

  const showdrawer = ref(false);
  const titledrawer = ref('');

  const rules: FormRules = {
    project: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请选择项目',
    },
    group: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请选择班组',
    },
    groupleader: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入班组长姓名',
    },
    groupstaffsize: [
      { required: true, trigger: ['blur', 'input'], message: '请输入班组人数' },
    ],
  };

  const formParams = reactive({
    project: '',
    group: '',
    groupleader: '',
    groupstaffsize: 0,

  });

  function showUserdrawer() {
    showdrawer.value = true;
    titledrawer.value = '新建班组';
    formParams.project = '';
    formParams.group = '';
    formParams.groupleader = '';
    formParams.groupstaffsize = 0;
  }
 
  interface FileInfo {
    id: string;
    name: string;
    batchId?: string | null;
    percentage?: number | null;
    status: 'pending' | 'uploading' | 'finished' | 'removed' | 'error';
    url?: string | null;
    file?: File | null;
    thumbnailUrl?: string | null;
    type?: string | null;
    fullPath?: string | null;
  }
 
  interface UploadCustomRequestOptions {
    file: FileInfo;
    action?: string;
    data?: Record<string, string> | (({ file }: { file: FileInfo }) => Record<string, string>);
    withCredentials?: boolean;
    headers?: Record<string, string> | (({ file }: { file: FileInfo }) => Record<string, string>);
    onProgress: (e: { percent: number }) => void;
    onFinish: () => void;
    onError: () => void;
  }

  const uploadComponent = ref(null);
  //上传
  const customRequest = async ({ file }: UploadCustomRequestOptions) => {
    await uploadGroupExcel(file).then(() => {
      window['$message'].success('导入成功');
      if (uploadComponent.value) {
        uploadComponent.value.clear();
      }
      reloadTable();
    });

  };

  function saveuserinfo() {
    window['$loading'].start();
    formRef.value.validate(async (errors) => {
      if (!errors) {
        if (titledrawer.value == "编辑班组") {
          // 编辑用户
          await updateGroup(formParams);
          window['$message'].success('编辑成功');
        } else {
          // 创建用户
          await createGroup(formParams);
          window['$message'].success('新建成功');
        }
        setTimeout(() => {
          showdrawer.value = false;
          reloadTable();
        });
      } else {
        window['$message'].error('请输入完整信息');
      }
      window['$loading'].finish();
    });
  }

  // 数据表格部分的actionColumn
  const actionColumn = reactive({
    width: 220,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '删除',
            onClick: handleDelete.bind(null, record),
            // 根据业务控制是否显示 isShow 和 auth 是并且关系
            ifShow: () => {
              return true;
            },
            // 根据权限控制是否显示: 有权限，会显示，支持多个
            // auth: ['basic_list'],
          },
          {
            label: '编辑',
            onClick: handleEdit.bind(null, record),
            ifShow: () => {
              return true;
            },
            // auth: ['basic_list'],
          },
        ],
      });
    },
  });

  // 加载数据表
  const loadDataTable = async (res) => {
    const data = await getTableList({ ...getFieldsValue(), ...res });
    console.log('loadDataTableRes:', data);
    return data;
  };

  //cdx：其他地方使用rowKeys，需要将其定义为一个响应式变量
  const rowKeys = ref([]);
  function onCheckedRow(rKeys) {
    console.log('选中的行数据', rKeys);
    rowKeys.value = rKeys;
    console.log('rowKeys.value', rowKeys.value.length);
  }

  //cdx：控制删除按钮是否可以点击，计算选中数据list的length是否为0。奇怪的是，直接在组件绑定“rowKeys.value.length === 0”会报错，转换为计算属性即可
  const isRowKeysEmpty = computed(() => {
    return rowKeys.value.length === 0;
  });

  function reloadTable() {
    actionRef.value.reload();
  }

  async function getgroupexcel() {
    const data = await getGroupExcel({...getFieldsValue()});
    return data;
  }

  function exportGroup() {
    window['$loading'].start();
    getgroupexcel().then((response) => {
      const url = window.URL.createObjectURL(response.data)
      const fileName = '班组信息（导出）.xlsx';
      let a = document.createElement('a');
      a.download = fileName;
      a.href = url;
      document.body.append(a);
      a.click();
      URL.revokeObjectURL(a.href);
      a.remove();
      window['$loading'].finish();
    });
  }


  // cdx：表格里面的编辑按钮对应的函数
  async function handleEdit(record: Recordable) {
    showdrawer.value = true;
    titledrawer.value = '编辑班组';
    formParams.project = record.project;
    formParams.group = record.group;
    formParams.groupleader = record.groupleader;
    formParams.groupstaffsize = record.groupstaffsize;
    projectReadOnly.value = true;
    groupReadOnly.value = true;
  }

  async function handleDelete(record: Recordable) {
    window['$loading'].start();
    try {
      const res = await batchDelGroup({ delGroupList: [record.id] });
      reloadTable();
      window['$message'].success('删除成功');
      window['$loading'].finish();
    } catch (error) {
      console.error('批量删除失败：', error);
    }
  }
  // cdx：表格上方的批量删除按钮对应的函数
  async function batchDelete() {
    window['$loading'].start();
    try {
      const res = await batchDelGroup({ delGroupList: rowKeys.value });
      reloadTable();
      window['$message'].success('删除成功');
      window['$loading'].finish();
      console.log('batchDelRes:', res);
    } catch (error) {
      console.error('批量删除失败：', error);
    }
  }

  async function handleSubmit(values: Recordable) {
    window['$loading'].start();
    reloadTable();
    window['$loading'].finish();

  }

  function handleReset(values: Recordable) {
    console.log(values);

  }
</script>

<style lang="less" scoped>
</style>
